package com.mls.guardian.remoting.netty;



import com.mls.guardian.protocol.RemoteCommand;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;

/**
 * Created by jl on 15/9/8.
 */
public class NettyEncoder extends MessageToByteEncoder<RemoteCommand>  {
    private static final Logger log = LoggerFactory.getLogger(NettyEncoder.class);
    @Override
    protected void encode(ChannelHandlerContext ctx, RemoteCommand msg, ByteBuf out) throws Exception {
        try{
            ByteBuffer byteBuf = RemoteCommand.encode(msg);
            out.writeBytes(byteBuf);
        }catch(Exception e){
//            log.error("encode exception, " + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), e);
            if (msg != null) {
                log.error("encode msg error ",e);
            }


            ctx.channel().close();
        }
    }
}
